#!/bin/bash

# 检查是否以 root 用户运行
if [ "$EUID" -ne 0 ]; then
    echo "请以 root 用户运行此脚本。"
    exit 1
fi

# 定义备份和日志目录
BASE_DIR="/etc/adn"
BACKUP_DIR="$BASE_DIR/backup"
LOG_DIR="$BASE_DIR/log"

# 创建必要的目录
mkdir -p "$BACKUP_DIR"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/network_config.log"

# 记录日志函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# 检查并安装依赖
check_and_install_dependencies() {
    PACKAGES=("iproute2" "systemd")
    for pkg in "${PACKAGES[@]}"; do
        if ! dpkg -s "$pkg" >/dev/null 2>&1; then
            log "检测到 $pkg 未安装，开始安装..."
            apt-get update
            apt-get install -y "$pkg"
            if [ $? -eq 0 ]; then
                log "$pkg 安装成功"
            else
                log "安装 $pkg 失败，请手动检查"
                echo "安装 $pkg 失败，请手动检查"
                exit 1
            fi
        fi
    done
}

# 调用依赖检查函数
check_and_install_dependencies()

# 检索 Debian 版本
debian_version=$(cat /etc/debian_version | cut -d. -f1)

# 检索网络接口名称
interfaces=()
while IFS= read -r line; do
    interfaces+=("$line")
done < <(ip -o link show | awk -F': ' '{print $2}')

# 主菜单函数
show_menu() {
    echo "请选择操作："
    echo "1. 配置网络"
    echo "2. 恢复网络配置备份"
    echo "3. 安装脚本"
    echo "4. 卸载脚本及产生的文件"
    echo "5. 退出"
    read -p "请输入选项编号: " choice
    case $choice in
        1)
            configure_network
            ;;
        2)
            restore_backup
            ;;
        3)
            install_script
            ;;
        4)
            uninstall_script
            ;;
        5)
            exit 0
            ;;
        *)
            echo "无效的选项，请重新输入。"
            show_menu
            ;;
    esac
}

# 配置网络函数
configure_network() {
    # 显示网络接口列表并询问用户
    echo "检测到以下网络接口："
    for i in "${!interfaces[@]}"; do
        echo "$((i + 1)). ${interfaces[$i]}"
    done

    read -p "请选择要配置的网络接口编号（输入数字）: " choice
    if [[ $choice -lt 1 || $choice -gt ${#interfaces[@]} ]]; then
        echo "输入的编号无效，操作取消。"
        show_menu
    fi
    interface=${interfaces[$((choice - 1))]}

    read -p "你选择的网络接口是 $interface，确认吗？(Y/N): " confirm
    if [ "$confirm" != "Y" ] && [ "$confirm" != "y" ]; then
        echo "操作取消。"
        show_menu
    fi

    # 函数：配置使用 /etc/network/interfaces
    configure_network_interfaces() {
        read -p "请输入静态 IP 地址（例如 192.168.1.100）: " ip_address
        read -p "请输入子网掩码（例如 255.255.255.0）: " netmask
        read -p "请输入网关地址（例如 192.168.1.1）: " gateway
        read -p "请输入 DNS 服务器地址（例如 8.8.8.8）: " dns_server

        echo "你输入的配置信息如下："
        echo "网络接口: $interface"
        echo "IP 地址: $ip_address"
        echo "子网掩码: $netmask"
        echo "网关地址: $gateway"
        echo "DNS 服务器: $dns_server"

        read -p "确认使用以上配置吗？(Y/N): " confirm
        if [ "$confirm" = "Y" ] || [ "$confirm" = "y" ]; then
            # 备份原始网络配置文件
            cp /etc/network/interfaces "$BACKUP_DIR/interfaces_$(date '+%Y%m%d%H%M%S')"
            log "备份 /etc/network/interfaces 到 $BACKUP_DIR/interfaces_$(date '+%Y%m%d%H%M%S')"

            # 写入新的网络配置
            cat << EOF > /etc/network/interfaces
# 本地环回接口
auto lo
iface lo inet loopback

# 配置指定的网络接口为静态 IP
auto $interface
iface $interface inet static
    address $ip_address
    netmask $netmask
    gateway $gateway
EOF

            # 配置 DNS
            cp /etc/resolv.conf "$BACKUP_DIR/resolv.conf_$(date '+%Y%m%d%H%M%S')"
            log "备份 /etc/resolv.conf 到 $BACKUP_DIR/resolv.conf_$(date '+%Y%m%d%H%M%S')"
            echo "nameserver $dns_server" > /etc/resolv.conf

            # 重启网络服务
            ifdown $interface
            ifup $interface

            echo "网络配置已更新。"
            log "网络配置更新成功，使用 /etc/network/interfaces 配置方式"
        else
            echo "配置未保存，操作取消。"
            show_menu
        fi
    }

    # 函数：配置使用 systemd-networkd
    configure_systemd_networkd() {
        read -p "请输入静态 IP 地址（例如 192.168.1.100/24）: " ip_address
        read -p "请输入网关地址（例如 192.168.1.1）: " gateway
        read -p "请输入 DNS 服务器地址（例如 8.8.8.8）: " dns_server

        echo "你输入的配置信息如下："
        echo "网络接口: $interface"
        echo "IP 地址: $ip_address"
        echo "网关地址: $gateway"
        echo "DNS 服务器: $dns_server"

        read -p "确认使用以上配置吗？(Y/N): " confirm
        if [ "$confirm" = "Y" ] || [ "$confirm" = "y" ]; then
            # 备份原始网络配置文件
            cp /etc/systemd/network/00-$interface.network "$BACKUP_DIR/00-$interface.network_$(date '+%Y%m%d%H%M%S')" 2>/dev/null
            log "备份 /etc/systemd/network/00-$interface.network 到 $BACKUP_DIR/00-$interface.network_$(date '+%Y%m%d%H%M%S')"

            # 写入新的网络配置
            cat << EOF > /etc/systemd/network/00-$interface.network
[Match]
Name=$interface

[Network]
Address=$ip_address
Gateway=$gateway
DNS=$dns_server
EOF

            # 重启 systemd-networkd 服务
            systemctl restart systemd-networkd

            echo "网络配置已更新。"
            log "网络配置更新成功，使用 systemd-networkd 配置方式"
        else
            echo "配置未保存，操作取消。"
            show_menu
        fi
    }

    # 根据 Debian 版本选择配置方法
    if [ "$debian_version" -lt 10 ]; then
        echo "检测到 Debian 版本小于 10，将使用 /etc/network/interfaces 进行配置。"
        configure_network_interfaces
    else
        echo "检测到 Debian 版本大于等于 10，将使用 systemd-networkd 进行配置。"
        configure_systemd_networkd
    fi
    show_menu
}

# 恢复备份函数
restore_backup() {
    echo "可用的备份文件："
    backup_files=($(ls $BACKUP_DIR))
    for i in "${!backup_files[@]}"; do
        echo "$((i + 1)). ${backup_files[$i]}"
    done
    read -p "请选择要恢复的备份文件编号（输入数字）: " choice
    if [[ $choice -lt 1 || $choice -gt ${#backup_files[@]} ]]; then
        echo "输入的编号无效，操作取消。"
        show_menu
    fi
    backup_file="${backup_files[$((choice - 1))]}"
    if [[ $backup_file == interfaces* ]]; then
        cp "$BACKUP_DIR/$backup_file" /etc/network/interfaces
        log "从 $BACKUP_DIR/$backup_file 恢复 /etc/network/interfaces"
        ifdown $(ip -o link show | awk -F': ' '{print $2}' | grep -v lo | head -n 1)
        ifup $(ip -o link show | awk -F': ' '{print $2}' | grep -v lo | head -n 1)
    elif [[ $backup_file == resolv.conf* ]]; then
        cp "$BACKUP_DIR/$backup_file" /etc/resolv.conf
        log "从 $BACKUP_DIR/$backup_file 恢复 /etc/resolv.conf"
    elif [[ $backup_file == *network ]]; then
        interface=$(echo $backup_file | cut -d. -f1 | cut -d- -f2)
        cp "$BACKUP_DIR/$backup_file" /etc/systemd/network/00-$interface.network
        log "从 $BACKUP_DIR/$backup_file 恢复 /etc/systemd/network/00-$interface.network"
        systemctl restart systemd-networkd
    fi
    echo "备份恢复成功。"
    show_menu
}

# 安装脚本函数
install_script() {
    cp "$0" /usr/local/bin/auto-debian-network.sh
    chmod +x /usr/local/bin/auto-debian-network.sh
    echo "脚本已安装到 /usr/local/bin/auto-debian-network.sh"
    log "脚本安装到 /usr/local/bin/auto-debian-network.sh"
    show_menu
}

# 卸载脚本及产生的文件函数
uninstall_script() {
    rm -f /usr/local/bin/auto-debian-network.sh
    rm -rf "$BASE_DIR"
    echo "脚本及产生的文件已卸载。"
    log "脚本及产生的文件卸载"
    exit 0
}

# 显示主菜单
show_menu